"""
商品模型
"""
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

from app import db


class Product(db.Model):
    """商品模型"""
    __tablename__ = 'products'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text)
    price = db.Column(db.Float, nullable=False)
    category = db.Column(db.String(100), nullable=False)
    stock_quantity = db.Column(db.Integer, default=0)
    image_url = db.Column(db.String(500))
    is_available = db.Column(db.Boolean, default=True)
    rating = db.Column(db.Float, default=0.0)
    review_count = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    order_items = db.relationship('OrderItem', backref='product', lazy=True)
    
    def __init__(self, name, price, category, description=None, stock_quantity=0, 
                 image_url=None, is_available=True):
        self.name = name
        self.price = price
        self.category = category
        self.description = description
        self.stock_quantity = stock_quantity
        self.image_url = image_url
        self.is_available = is_available
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'price': self.price,
            'category': self.category,
            'stock_quantity': self.stock_quantity,
            'image_url': self.image_url,
            'is_available': self.is_available,
            'rating': self.rating,
            'review_count': self.review_count,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def __repr__(self):
        return f'<Product {self.name}>'
    
    def update_stock(self, quantity):
        """更新库存"""
        self.stock_quantity += quantity
        if self.stock_quantity < 0:
            self.stock_quantity = 0
        
        # 如果库存为0，标记为不可用
        if self.stock_quantity == 0:
            self.is_available = False
        elif self.stock_quantity > 0 and not self.is_available:
            self.is_available = True
    
    def update_rating(self, new_rating):
        """更新评分"""
        total_rating = self.rating * self.review_count
        self.review_count += 1
        self.rating = (total_rating + new_rating) / self.review_count
    
    @classmethod
    def find_by_id(cls, product_id):
        """根据ID查找商品"""
        return cls.query.get(product_id)
    
    @classmethod
    def find_by_category(cls, category):
        """根据分类查找商品"""
        return cls.query.filter_by(category=category, is_available=True).all()
    
    @classmethod
    def search_products(cls, keyword):
        """搜索商品"""
        return cls.query.filter(
            cls.name.ilike(f'%{keyword}%') | 
            cls.description.ilike(f'%{keyword}%'),
            cls.is_available == True
        ).all()
    
    @classmethod
    def get_available_products(cls):
        """获取所有可用商品"""
        return cls.query.filter_by(is_available=True).all()
    
    @classmethod
    def get_low_stock_products(cls, threshold=10):
        """获取低库存商品"""
        return cls.query.filter(
            cls.stock_quantity <= threshold,
            cls.is_available == True
        ).all()